<template>
  <div class="friends">
    <div>
      <el-input v-model="input1" class="w-50 m-2" size="large" placeholder="请输入对方用户名" :prefix-icon="Search" />
      <el-button @click="handleSearchUser">搜索</el-button>
    </div>
    <div class="friends-info" v-if="friendInfo.name">
      <span>name: {{ friendInfo.name }}</span>
      <el-button @click="handleAddFriend">添加好友</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue"
import { Search } from '@element-plus/icons-vue'
import { getUserInfo, addFriends } from "@/api/user/index"
import { ElMessage } from "element-plus";
import { userStore } from "@/store/user";
const input1 = ref("")
const friendInfo = reactive({
  name: "",
  article: "",
  id: ""
})

const user_store = userStore()
const userInfo = user_store.$state.userInfo

// 搜索用户
const handleSearchUser = async () => {
  const data = await getUserInfo(input1.value.toString())
  if (data.data.status === 400) {
    friendInfo.name = ""
    return ElMessage("该用户不存在")
  }
  friendInfo.name = data.data.data.nickname
  friendInfo.id = data.data.data._id
  console.log(data, 'data');
}

// 添加用户
const handleAddFriend = async () => {
  const info = localStorage.getItem('userInfo')
  const data = {
    u_id: userInfo._id,
    friend_id: friendInfo.id,
    userInfo: info || ''
  }
  const res = await addFriends(data)
  if (res.data.status == 400) {
    return ElMessage(res.data.message)
  }
  ElMessage(res.data.messgae)
}
</script>

<style lang="less" scoped>
.friends {
  display: flex;
  flex-direction: column;
}
</style>